package com.common.util;



import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class BigDecimalUtil {


    public static String formatToNumber(BigDecimal obj, String pattern) {
        StringBuilder p = new StringBuilder();
        if (obj == null) {
            p.append("0").append(pattern);
            obj = new BigDecimal(p.toString());
        }
        p = new StringBuilder();
        p.append("#").append(pattern);
        DecimalFormat df = new DecimalFormat(p.toString());
        int compareTo = obj.compareTo(BigDecimal.ZERO);
        BigDecimal bigDecimal = new BigDecimal(1);
        BigDecimal decimal = new BigDecimal(-1);
        if (compareTo == 0) {
            return "0" + pattern;
        }
        if (compareTo > 0 && obj.compareTo(bigDecimal) < 0) {
            return "0" + df.format(obj);
        }
        if (compareTo < 0 && obj.compareTo(decimal) > 0) {
            df = new DecimalFormat("0" + pattern);
            return df.format(obj);
        }
        return df.format(obj);
    }

    public static String formatToNumber(String obj, String pattern) {
        if (StringUtils.isBlank(obj)) {
            obj = "0" + pattern;
        }
        return formatToNumber(new BigDecimal(obj), pattern);
    }

    public static String formatToNumber(BigDecimal obj) {
        return formatToNumber(obj, ".00");
    }

    public static String formatToNumber(String obj) {
        return formatToNumber(obj, ".00");
    }


}
